﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DBHelper;
using Lohus.Model;
using System.Data.OleDb;
using Models;
using System.Web.Security;
using System.Collections;
using System.IO;
using System.Globalization;

namespace Lohus.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            return View();
        }
        public ActionResult Login()
        {
            return View();
        }
        /// <summary>
        /// 登录验证
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public ActionResult MyLogin(string name, string pwd)
        {
            name = name.Trim('\'');
            pwd = pwd.Trim('\'');
            pwd = DESEncrypt.Encrypt(pwd);
            string sql = "select count(0) from users where username='" + name + "' and pwd='" + pwd + "'";

            if (DBHelper.DBHelper.Exists(sql))
            {
                User user = new User() { UserName = name, Pwd = pwd };
                Ticket.MyTicket = user;
                Session["ticket"] = user;
                FormsAuthentication.SetAuthCookie("user", false);
                //return RedirectToAction("BackMain", "Home");
                return Json("true", JsonRequestBehavior.AllowGet);
            }
            else
            {
                //return View("Login");
                return Json("Error", JsonRequestBehavior.AllowGet);
            }

        }
        /// <summary>
        /// 后台管理主页
        /// </summary>
        /// <returns></returns>
        public ActionResult BackMain()
        {
            if (FormsAuthentication.GetAuthCookie("user", false) == null)
            {
                return View("Login");
            }
            return View();
        }

        public ActionResult CaseArticle(string ID)
        {
            if (!string.IsNullOrEmpty(ID))
            {
                ID = ID.Trim('\'');
                string sql = @"SELECT   Article.ID, Article.CategoryID, Article.ArticleName, Article.Content, Article.CreateTime, Article.[Order], 
                           caseCategories.classname
                           FROM      (Article LEFT OUTER JOIN
                           CaseCategories ON Article.CategoryID = CaseCategories.ID) where Article.id=" + ID;

                ArticleExt article = new ArticleExt();
                using (OleDbConnection con = new OleDbConnection(DBHelper.DBHelper.connectionString))
                {
                    con.Open();
                    OleDbCommand cmd = new OleDbCommand(sql, con);
                    using (OleDbDataReader dr = cmd.ExecuteReader())
                    {
                        if (dr != null)
                        {
                            while (dr.Read())
                            {
                                ViewData["ID"] = Convert.ToInt32(dr["ID"].ToString());
                                ViewData["Title"] = dr["ArticleName"].ToString();
                                ViewData["Content"] = dr["Content"].ToString();
                                ViewData["CategoryID"] = dr["CategoryID"].ToString();
                                ViewData["CreateTime"] = Convert.ToDateTime(dr["CreateTime"].ToString());
                                ViewData["CategoryName"] = dr["ClassName"].ToString();
                            }
                        }
                    }
                }
            }
            return View();
        }
        public ActionResult ServiceArticle(string ID)
        {
            if (FormsAuthentication.GetAuthCookie("user", false) == null)
            {
                throw new Exception("无访问权限！");
            }
            return View();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="title"></param>
        /// <param name="pre">简述</param>
        /// <param name="Content"></param>
        /// <returns></returns>
        [ValidateInput(false)]
        public ActionResult AddArticle(string title, string pre, string Content, string cid,string id)
        {
            if (FormsAuthentication.GetAuthCookie("user", false) == null)
            {
                throw new Exception("无访问权限！");
            }

            if (string.IsNullOrEmpty(title))
            {
                return Json(0, JsonRequestBehavior.AllowGet);
            }
            string sql = "";
            /// 如果ID不为空，那么更新文章
            if (!string.IsNullOrEmpty(id))
            {
                sql = "update service set title = '{0}',content='{1}',preview='{2}',categoryID = {3} where id = {4}";
                sql = string.Format(sql, title, Content, pre, cid, id);

            }
            else
            {
                sql = "insert into service(title,content,preview,categoryID) values('{0}','{1}','{2}',{3})";
                sql = string.Format(sql, title, Content, pre, cid);
            }
            using (OleDbConnection con = new OleDbConnection(DBHelper.DBHelper.connectionString))
            {
                try
                {
                    con.Open();
                    OleDbCommand cmd = new OleDbCommand(sql, con);
                    int i = cmd.ExecuteNonQuery();
                    return Json(i, JsonRequestBehavior.AllowGet);
                }
                catch
                {
                    return Json(0, JsonRequestBehavior.AllowGet);
                }

            }
        }
        /// <summary>
        /// 获取服务类型分类
        /// </summary>
        /// <returns></returns>
        public ActionResult GetServiceCategories()
        {
            string sql = "select * from ServiceCategories";
            List<ServiceCategories> result = new List<ServiceCategories>();
            using (OleDbConnection con = new OleDbConnection(DBHelper.DBHelper.connectionString))
            {
                con.Open();
                OleDbCommand cmd = new OleDbCommand(sql, con);
                using (OleDbDataReader dr = cmd.ExecuteReader())
                {

                    if (dr != null)
                    {
                        while (dr.Read())
                        {
                            ServiceCategories category = new ServiceCategories();
                            category.ID = Convert.ToInt32(dr["ID"].ToString());
                            category.Img = dr["Img"].ToString();
                            category.SName = dr["SName"].ToString();
                            result.Add(category);
                        }
                    }
                }
                ViewData["result"] = result;
            }
            result.Reverse();
            return Json(result, JsonRequestBehavior.AllowGet);

        }

        public ActionResult ThinkingArticle()
        {
            return View();
        }
        /// <summary>
        /// 获取罗豪斯思想介绍文章
        /// </summary>
        /// <returns></returns>
        public ActionResult GetThinkingArticle()
        {
            string sql = "select top 1 id,content from thinkingArticle order by id desc";
            using (OleDbConnection con = new OleDbConnection(DBHelper.DBHelper.connectionString))
            {
                try
                {
                    con.Open();
                    OleDbCommand cmd = new OleDbCommand(sql, con);
                    using (OleDbDataReader dr = cmd.ExecuteReader())
                    {
                        if (dr != null)
                        {
                            while (dr.Read())
                            {
                                ThinkingArticle article = new ThinkingArticle();
                                article.ID = Convert.ToInt32(dr["id"].ToString());
                                article.Content = dr["content"].ToString();
                                return Json(article, JsonRequestBehavior.AllowGet);
                            }
                        }
                        else
                        {
                            return Json(new ThinkingArticle(), JsonRequestBehavior.AllowGet);
                        }
                    }
                }
                catch
                {
                    return Json(new ThinkingArticle(), JsonRequestBehavior.AllowGet);
                }
            }
            return Json(new ThinkingArticle(), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 保存罗豪斯思想文章
        /// </summary>
        /// <param name="ID"></param>
        /// <param name="Content"></param>
        /// <returns></returns>
        [ValidateInput(false)]
        public ActionResult SaveThinkingArticle(string ID, string Content)
        {
            if (FormsAuthentication.GetAuthCookie("user", false) == null)
            {
                throw new Exception("无访问权限！");
            }
            if (string.IsNullOrEmpty(Content))
            {
                return Json(0, JsonRequestBehavior.AllowGet);
            }
            if (string.IsNullOrEmpty(Content))
            {
                Content = Content.Trim('\'');
            }
            string sql = "";
            if (string.IsNullOrEmpty(ID))
            {
                ID = "1";
                sql = "insert into thinkingarticle(content,id) values('" + Content + "'," + ID + ")";
            }
            else
            {
                sql = "update thinkingarticle set content  = '" + Content + "' where id =" + ID;
            }
            using (OleDbConnection con = new OleDbConnection(DBHelper.DBHelper.connectionString))
            {
                try
                {
                    con.Open();
                    OleDbCommand cmd = new OleDbCommand(sql, con);
                    return Json(cmd.ExecuteNonQuery(), JsonRequestBehavior.AllowGet);
                }
                catch
                {
                    return Json(0, JsonRequestBehavior.AllowGet);
                }
            }
        }
        #region ChangePwd
        public ActionResult ChangePwd()
        {


            if (FormsAuthentication.GetAuthCookie("user", false) == null)
            {
                throw new Exception("无访问权限！");
            }
            return View();
        }
        public ActionResult ChangeMyPwd(string oldPwd, string newPwd)
        {

            if (FormsAuthentication.GetAuthCookie("user", false) == null)
            {
                throw new Exception("无访问权限！");
            }
            oldPwd = oldPwd.Trim('\'');
            newPwd = newPwd.Trim('\'');
            HttpCookie a = FormsAuthentication.GetAuthCookie("user", false);
            string username = a.Value;
            string checkExist = "select count(0) from users where pwd = '" + DESEncrypt.Encrypt(oldPwd) + "'";
            using (OleDbConnection con = new OleDbConnection(DBHelper.DBHelper.connectionString))
            {
                try
                {
                    con.Open();
                    OleDbCommand cdm = new OleDbCommand(checkExist, con);
                    if (Convert.ToInt16(cdm.ExecuteScalar()) > 0)
                    {
                        string sql = "update Users set pwd = '" + DESEncrypt.Encrypt(newPwd) + "'";
                        OleDbCommand cmd = new OleDbCommand(sql, con);
                        return Json(cmd.ExecuteNonQuery() > 0, JsonRequestBehavior.AllowGet);
                    }
                    else
                    {
                        return Json(false, JsonRequestBehavior.AllowGet);
                    }
                }
                catch
                {
                    return Json(false, JsonRequestBehavior.AllowGet);
                }
            }
        }
        #endregion

        #region 图片上传

        /// <summary>
        /// 图片上传
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Upload()
        {
            string savePath = "../Content/Images/Upload/";
            string saveUrl = "../../Content/Images/Upload/";
            string fileTypes = "gif,jpg,jpeg,png,bmp";
            int maxSize = 1000000;

            Hashtable hash = new Hashtable();

            HttpPostedFileBase file = Request.Files["imgFile"];
            if (file == null)
            {
                hash = new Hashtable();
                hash["error"] = 0;
                hash["url"] = "请选择文件";
                return Json(hash);
            }

            string dirPath = Server.MapPath(savePath);
            if (!Directory.Exists(dirPath))
            {
                hash = new Hashtable();
                hash["error"] = 0;
                hash["url"] = "上传目录不存在";
                return Json(hash);
            }

            string fileName = file.FileName;
            string fileExt = Path.GetExtension(fileName).ToLower();

            ArrayList fileTypeList = ArrayList.Adapter(fileTypes.Split(','));

            if (file.InputStream == null || file.InputStream.Length > maxSize)
            {
                hash = new Hashtable();
                hash["error"] = 0;
                hash["url"] = "上传文件大小超过限制";
                return Json(hash);
            }

            if (string.IsNullOrEmpty(fileExt) || Array.IndexOf(fileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1)
            {
                hash = new Hashtable();
                hash["error"] = 0;
                hash["url"] = "上传文件扩展名是不允许的扩展名";
                return Json(hash);
            }

            string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
            string filePath = dirPath + newFileName;
            file.SaveAs(filePath);
            string fileUrl = saveUrl + newFileName;

            hash = new Hashtable();
            hash["error"] = 0;
            hash["url"] = fileUrl;

            return Json(hash, "text/html;charset=UTF-8"); ;
        }

        #endregion
    }
}
